package com.hang.gymmanager.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hang.gymmanager.Enum.CommonConstant;
import com.hang.gymmanager.Enum.CommonEnum;
import com.hang.gymmanager.entity.UserInfoEntity;
import com.hang.gymmanager.exception.BusinessException;
import com.hang.gymmanager.mapper.UserInfoMapper;
import com.hang.gymmanager.req.LoginReq;
import com.hang.gymmanager.service.LoginService;
import com.hang.gymmanager.util.CacheTool;
import com.hang.gymmanager.util.PasswordEncodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author wyq
 * @version v1.0.0
 * @explain
 * @date 2024/3/14 14:44
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LoginServiceImpl implements LoginService {

    private final UserInfoMapper userInfoMapper;
    private final CacheTool cacheTool;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String login(LoginReq req) {
        //1.先验证账号密码
        String unCode = req.getPassword();
        String enCode = PasswordEncodeUtil.passwordEncode(unCode, CommonConstant.PASSWORD_SALT);
        QueryWrapper<UserInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(UserInfoEntity::getTelephone,req.getTelephone())
                .eq(UserInfoEntity::getPassword,enCode);
        UserInfoEntity userInfoEntity = userInfoMapper.selectOne(wrapper);
        if(ObjectUtil.isNull(userInfoEntity)){
            throw new BusinessException("手机号或密码错误");
        }
        if(userInfoEntity.getRecFlag().equals(CommonEnum.NO.getValue())){
            throw new BusinessException("用户已被禁用");
        }
        Integer userId = userInfoEntity.getUserId();
        //token过期时间是系统当前时间加上定义的token有效期的时间戳(秒级)
        Long validSeconds = System.currentTimeMillis()/1000+CommonConstant.TOKEN_VALID_SECONDS;
        Map<String,Object> payloads = new HashMap<>();
        payloads.put("userId",userId);
        payloads.put("exp",validSeconds);
        String token = JWTUtil.createToken(payloads, CommonConstant.TOKEN_SIGN_KEY.getBytes());
        cacheTool.add(CommonConstant.TOKEN_PREFIX+userId,token);
        return token;
    }
}
